from faker import Faker
import pymysql
from datetime import datetime

# 创建 Faker 实例
fake = Faker()

# 连接到 MySQL 数据库
connection = pymysql.connect(
    host='localhost',  # 数据库地址
    user='root',  # 数据库用户名
    password='1234',  # 数据库密码
    database='db01'  # 数据库名称
)

try:
    with connection.cursor() as cursor:
        # 创建表的示例（如果表不存在）
        # create_table_query = """
        # CREATE TABLE IF NOT EXISTS users (
        #     id INT AUTO_INCREMENT PRIMARY KEY,
        #     name VARCHAR(255) NOT NULL,
        #     address VARCHAR(255) NOT NULL,
        #     email VARCHAR(255) NOT NULL,
        #     phone_number VARCHAR(255)
        # )
        # """
        # cursor.execute(create_table_query)

        # 生成并插入数据
        for _ in range(10):  # 生成10条数据
            name = fake.unique.company()  # 使用 unique 保证 name 唯一
            room = fake.random_element(elements=('Room A', 'Room B', 'Room C', 'Room D'))
            begin_date = fake.date_between(start_date='-1y', end_date='today')
            end_date = fake.date_between(start_date=begin_date, end_date='+1y')
            master_id = fake.random_int(min=1, max=100)
            subject = fake.random_element(elements=[1, 2, 3, 4, 5, 6])  # 对应学科编码
            create_time = datetime.now()
            update_time = datetime.now()

            insert_query = """
                INSERT INTO clazz (name, room, begin_date, end_date, master_id, subject, create_time, update_time)
                VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                """
            cursor.execute(insert_query,
                           (name, room, begin_date, end_date, master_id, subject, create_time, update_time))
    # 提交事务
    connection.commit()

finally:
    connection.close()

print("数据插入完成。")
